package com.atguigu.gulimall.order.service.impl;

import com.alibaba.fastjson.TypeReference;
import com.atguigu.common.exception.NoStockException;
import com.atguigu.common.to.SeckillOrderTo;
import com.atguigu.common.to.mq.OrderTo;
import com.atguigu.common.utils.R;
import com.atguigu.common.vo.MemberResponseVo;
import com.atguigu.gulimall.order.constant.OrderConstant;
import com.atguigu.gulimall.order.entity.OrderItemEntity;
import com.atguigu.gulimall.order.entity.PaymentInfoEntity;
import com.atguigu.gulimall.order.enume.OrderStatusEnum;
import com.atguigu.gulimall.order.feign.CartFeignService;
import com.atguigu.gulimall.order.feign.MemberFeignService;
import com.atguigu.gulimall.order.feign.ProductFeignService;
import com.atguigu.gulimall.order.feign.WmsFeignService;
import com.atguigu.gulimall.order.interceptor.LoginInterceptor;
import com.atguigu.gulimall.order.service.OrderItemService;
import com.atguigu.gulimall.order.service.PaymentInfoService;
import com.atguigu.gulimall.order.to.OrderCreateTo;
import com.atguigu.gulimall.order.vo.*;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import org.springframework.amqp.AmqpException;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;

import com.atguigu.gulimall.order.dao.OrderDao;
import com.atguigu.gulimall.order.entity.OrderEntity;
import com.atguigu.gulimall.order.service.OrderService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;


@Service("orderService")
public class OrderServiceImpl extends ServiceImpl<OrderDao, OrderEntity> implements OrderService {

    private ThreadLocal<OrderSubmitVo> submitThreadLocal = new ThreadLocal<>();

    @Autowired
    MemberFeignService memberFeignService;

    @Autowired
    CartFeignService cartFeignService;

    @Autowired
    ThreadPoolExecutor executor;

    @Autowired
    WmsFeignService wmsFeignService;

    @Autowired
    StringRedisTemplate redisTemplate;

    @Autowired
    ProductFeignService productFeignService;

    @Autowired
    OrderItemService orderItemService;

    @Autowired
    RabbitTemplate rabbitTemplate;

    @Autowired
    PaymentInfoService paymentInfoService;
    /**
     * 分页查询
     *
     * @param params
     * @return
     */
    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<OrderEntity> page = this.page(
                new Query<OrderEntity>().getPage(params),
                new QueryWrapper<OrderEntity>()
        );

        return new PageUtils(page);
    }

    /**
     * 返回需要的确认页数据
     *
     * @return
     */
    @Override
    public OrderConfirmVo confirmOrder() {
        OrderConfirmVo orderConfirmVo = new OrderConfirmVo();
        MemberResponseVo memberResponseVo = LoginInterceptor.loginUser.get();
        /* 获取订单线程中的 requestAttributes，在执行异步任务的时候 将其传给 其它服务的线程，这样
        Feign的请求头在异步编排任务下也不会丢失*/
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        CompletableFuture<Void> getAddressesFuture=null;
        CompletableFuture<Void> getCartItemsFuture=null;

        //查询收货地址 异步任务
        {
            getAddressesFuture = CompletableFuture.runAsync(() -> {
                RequestContextHolder.setRequestAttributes(requestAttributes);
                //1、远程查询用户所有收货地址
                List<MemberAddressVo> addresses = memberFeignService.getAddresses(memberResponseVo.getId());
                orderConfirmVo.setAddress(addresses);
            }, executor);
        }
        //查询购物项及库存   异步任务
        {
            getCartItemsFuture = CompletableFuture.runAsync(() -> {
                RequestContextHolder.setRequestAttributes(requestAttributes);
                //2、远程查询购物车所有选中的购物项,包括最新价格
                List<OrderItemVo> items = cartFeignService.getCurrentUserCartItems();
                orderConfirmVo.setItems(items);
            }, executor).thenRunAsync(() -> {
                List<OrderItemVo> items = orderConfirmVo.getItems();
                List<Long> collect = items.stream().map(item ->
                        item.getSkuId()
                ).collect(Collectors.toList());

                R skusHasStock = wmsFeignService.getSkusHasStock(collect);

                List<SkuHasStockVo> data = skusHasStock.getData(new TypeReference<List<SkuHasStockVo>>() {
                });
                if (data != null) {
                    Map<Long, Boolean> map = data.stream().collect(Collectors.toMap(SkuHasStockVo::getSkuId, SkuHasStockVo::getHasStock));
                    orderConfirmVo.setHasStock(map);  //map存了 <skuid，有没有库存>
                }
            });}
        //3、查询用户积分
        {
            Integer integration = memberResponseVo.getIntegration();
            orderConfirmVo.setIntegration(integration);
        }
        //4、其他数据自动计算
        //*******-------------*************//
        //TODO 5、防重令牌
        {
            String token = UUID.randomUUID().toString().replace("-", "");
            redisTemplate.opsForValue().set(OrderConstant.USER_ORDER_TOKEN_PREFIX + memberResponseVo.getId(), token);
            orderConfirmVo.setOrderToken(token);
        }
        //等待所有异步任务完成
        CompletableFuture.allOf(getAddressesFuture, getCartItemsFuture);
        return orderConfirmVo;
    }

    /**
     * 提交订单功能
     * 高并发不适合使用seata AT模式分布式事务
     *    @GlobalTransactional
     * @param vo
     * @return
     */
    @Override
    @Transactional  //c277-11:50
    public SubmitResponseVo submitOrder(OrderSubmitVo vo) {
        submitThreadLocal.set(vo);
        SubmitResponseVo responseVo = new SubmitResponseVo();
        MemberResponseVo memberResponseVo = LoginInterceptor.loginUser.get();
        responseVo.setCode(0);
        //1、验证令牌是否合法[令牌的对比和删除必须保证原子性]
        //0令牌失败   1删除成功
        String script = "if redis.call('get',KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end";
       //这里的防重令牌 是在 获取订单页的的逻辑confirmOrder里面生成的
        String orderToken = vo.getOrderToken();
        //原子化验证令牌和删除令牌这两个操作
        Long result = redisTemplate.execute
                (new DefaultRedisScript<Long>(script, Long.class),
                        Arrays.asList(OrderConstant.USER_ORDER_TOKEN_PREFIX
                                + memberResponseVo.getId()), orderToken);
        if (result == 0L) {
            //令牌验证失败
            responseVo.setCode(1);
            return responseVo;
        } else {
            //令牌验证成功
            //下单，去创建订单，验令牌，锁库存
            //1、创建订单、订单项等信息
            OrderCreateTo order = createOrder();
            //2、验价
            BigDecimal payAmount = order.getOrder().getPayAmount();
            BigDecimal payPrice = vo.getPayPrice();
           if(Math.abs(payAmount.subtract(payPrice).doubleValue())<0.01){
               //金额对比成功

               //3、保存订单
               saveOrder(order);
               //4、库存锁定，只要有异常回滚订单数据
               WareSkuLockVo lockVo = new WareSkuLockVo();
               lockVo.setOrderSn(order.getOrder().getOrderSn());
               List<OrderItemVo> locks = order.getOrderItems().stream().map(item -> {
                   OrderItemVo itemVo = new OrderItemVo();
                   itemVo.setSkuId(item.getSkuId());
                   itemVo.setCount(item.getSkuQuantity());
                   itemVo.setTitle(item.getSkuName());
                   return itemVo;
               }).collect(Collectors.toList());
               lockVo.setLocks(locks);
               //准备去锁库存了  ==》WareSkuServiceImpl:orderLockStock
               R r = wmsFeignService.orderLockStock(lockVo);
               if(r.getCode()==0){
                   //锁成功了
                   responseVo.setOrder(order.getOrder());
                   //5、远程扣减积分
                   // TODO 模拟订单异常
//                   int i = 10/0; //订单回滚，库存不回滚
                   //订单创建成功发送消息给mq  c299-3:41
                   rabbitTemplate.convertAndSend("order-event-exchange","order.create.order",order.getOrder());
                   return responseVo;
               }else{
                   //锁失败了
                    responseVo.setCode(3); // 这个是应该是在支付服务讲解中更新的代码 case 3:msg+="库存锁定失败，商品库存不足";
                   try {
                       throw new Exception("ddd"); //c283_3..更新
                   } catch (Exception e) {
                       return responseVo;
                   }
               }
           }else{
               responseVo.setCode(2);
               return responseVo;
           }

        }


//        String redisToken = redisTemplate.opsForValue().get(OrderConstant.USER_ORDER_TOKEN_PREFIX + memberResponseVo.getId());
//        if(orderToken!=null && orderToken.equals(redisToken)){
//            //令牌验证通过
//            redisTemplate.delete(OrderConstant.USER_ORDER_TOKEN_PREFIX + memberResponseVo.getId())
//        }
    }

    /**
     * 根据订单Id查询订单状态
     * @param orderSn
     * @return
     */
    @Override
    public OrderEntity getOrderByOrderSn(String orderSn) {
        OrderEntity order_sn = this.getOne(new QueryWrapper<OrderEntity>().eq("order_sn", orderSn));
        return order_sn;
    }

    /**
     * 关闭订单
     * @param entity
     */
    @Override
    public void closeOrder(OrderEntity entity) {
        /*关单之前一定要查，这个订单当前状态是什么，因为有些人已经将该订单支付完成了
        * 到这里的单子都是30分钟后的，那么如果状态还是"待支付"的，说明可以取消单子了
        * 如果单子是其它状态 如已支付的， 那么不用取消单子
        * */
        OrderEntity orderEntity = this.getById(entity.getId());
        //c299-7:16
        if(orderEntity.getStatus() == OrderStatusEnum.CREATE_NEW.getCode()){//CREATE_NEW(0,"待付款"),
            //这里是过期关单，所以单子的状态都是待支付
            OrderEntity update = new OrderEntity();
            update.setId(entity.getId());
            update.setStatus(OrderStatusEnum.CANCLED.getCode());
            this.updateById(update);
            OrderTo orderTo = new OrderTo();
            BeanUtils.copyProperties(orderEntity,orderTo);
            //发送给MQ
            try {
                //TODO 保证消息一定会发送出去，，每一个消息都可以做好日志记录，（给数据库保存每一个消息的详细信息）
                //TODO 定期扫描数据库将失败的消息再发送一遍
                rabbitTemplate.convertAndSend("order-event-exchange","order.release.other",orderTo);
            } catch (AmqpException e) {
                //TODO 将没发送成功的消息进行重试发送 这就是防止消息丢失方法之一
                e.printStackTrace();
            }

        }
    }

    /**
     * 获取当前订单的支付信息
     * @param orderSn
     * @return
     */
    @Override
    public PayVo getOrderPay(String orderSn) {
        PayVo payVo = new PayVo();
        OrderEntity order = this.getOrderByOrderSn(orderSn);
        BigDecimal totalAmount = order.getPayAmount().setScale(2, BigDecimal.ROUND_UP);
        payVo.setTotal_amount(totalAmount.toString());
        payVo.setOut_trade_no(order.getOrderSn());

        List<OrderItemEntity> order_sn = orderItemService.list(new QueryWrapper<OrderItemEntity>().eq("order_sn", orderSn));
        OrderItemEntity entity = order_sn.get(0);
        payVo.setSubject(entity.getSkuName());
        payVo.setBody(entity.getSkuAttrsVals());

        return payVo;
    }

    /**
     * 分页查登录用户的订单详情
     * @param params
     * @return
     */
    @Override
    public PageUtils queryPageWithItem(Map<String, Object> params) {
        MemberResponseVo memberResponseVo = LoginInterceptor.loginUser.get();
        IPage<OrderEntity> page = this.page(
                new Query<OrderEntity>().getPage(params),
                new QueryWrapper<OrderEntity>().eq("member_id",memberResponseVo.getId())
                        .orderByDesc("id")
        );
        List<OrderEntity> order_sn = page.getRecords().stream().map(order -> {
            List<OrderItemEntity> orderItemEntities = orderItemService.list(new QueryWrapper<OrderItemEntity>().eq("order_sn", order.getOrderSn()));
            order.setItemEntities(orderItemEntities);
            return order;
        }).collect(Collectors.toList());

        page.setRecords(order_sn);
        return new PageUtils(page);
    }

    /**
     *  处理支付宝返回数据
     * @param vo
     * @return
     */
    @Override
    public String handlePayResult(PayAsyncVo vo) {
        PaymentInfoEntity infoEntity = new PaymentInfoEntity();
        //保存交易流水
        infoEntity.setAlipayTradeNo(vo.getTrade_no());
        infoEntity.setOrderSn(vo.getOut_trade_no());
        infoEntity.setPaymentStatus(vo.getTrade_status());
        infoEntity.setCallbackTime(vo.getNotify_time());

        paymentInfoService.save(infoEntity);

        //2、收到支付宝发送的支付成功消息后，修改订单的状态信息
        if(vo.getTrade_status().equals("TRADE_SUCCESS")|| vo.getTrade_status().equals("TRADE_FINISHED")){
            //支付成功状态
            String outTradeNo = vo.getOut_trade_no();
            this.baseMapper.updateOrderStatus(outTradeNo,OrderStatusEnum.PAYED.getCode());
        }
        return "success";

    }

    /**
     * 创建秒杀单的详细信息
     */
    @Override
    public void createSeckillOrder(SeckillOrderTo seckillOrderTo) {
        // 保存订单信息
        OrderEntity orderEntity = new OrderEntity();
        orderEntity.setOrderSn(seckillOrderTo.getOrderSn());
        orderEntity.setMemberId(seckillOrderTo.getMemberId());
        orderEntity.setStatus(OrderStatusEnum.CREATE_NEW.getCode());
        BigDecimal multiply = seckillOrderTo.getSeckillPrice().multiply(new BigDecimal("" + seckillOrderTo.getNum()));
        orderEntity.setPayAmount(multiply);
        this.save(orderEntity);

        //保存订单项信息
        OrderItemEntity orderItemEntity = new OrderItemEntity();
        orderItemEntity.setOrderSn(seckillOrderTo.getOrderSn());
        orderItemEntity.setRealAmount(multiply);
        orderItemEntity.setSkuQuantity(seckillOrderTo.getNum());
        //TODO 获取当前sku的详细信息进行设置          productFeignService。getSpuInfoBySkuId()
        orderItemService.save(orderItemEntity);
    }

    /**
     * 保存订单数据
     */
    private void saveOrder(OrderCreateTo order) {
        OrderEntity orderEntity = order.getOrder();
        orderEntity.setModifyTime(new Date());
        this.save(orderEntity);
        List<OrderItemEntity> orderItems = order.getOrderItems();
        orderItemService.saveBatch(orderItems);

    }

    private OrderCreateTo  createOrder() {
        OrderCreateTo createTo = new OrderCreateTo();
        //1、生产订单编号  C278-4:50
        String ordersn = IdWorker.getTimeId();
        OrderEntity orderEntity = buildOrder(ordersn);

        //2、从购物车中获取到所有的订单项
        List<OrderItemEntity> itemEntities = buildOrderItems(ordersn);

        //3、计算价格、积分等相关
        computePrice(orderEntity,itemEntities);

        createTo.setOrder(orderEntity);
        createTo.setOrderItems(itemEntities);

        return createTo;
    }

    /**
     * 计算价格相关
     * @param orderEntity
     * @param itemEntities
     */
    private void computePrice(OrderEntity orderEntity, List<OrderItemEntity> itemEntities) {
        BigDecimal total = new BigDecimal("0.0"); //总额
        BigDecimal coupon = new BigDecimal("0.0"); //优惠券
        BigDecimal integration = new BigDecimal("0.0"); //积分
        BigDecimal promotion = new BigDecimal("0.0"); //打折

        BigDecimal gift = new BigDecimal("0.0");
        BigDecimal growth = new BigDecimal("0.0");
        //订单总额，叠加每一个订单项的总额信息
        for (OrderItemEntity entity : itemEntities) {
            coupon = coupon.add(entity.getCouponAmount());
            integration = integration.add(entity.getIntegrationAmount());
            promotion = promotion.add(entity.getPromotionAmount());
            total = total.add(entity.getRealAmount());
            gift = gift.add(new BigDecimal(entity.getGiftIntegration().toString()));
            growth = growth.add(new BigDecimal(entity.getGiftGrowth().toString()));
        }
        //1、订单价格相关
        orderEntity.setTotalAmount(total);
        //应付总额
        orderEntity.setPayAmount(total.add(orderEntity.getFreightAmount()));

        orderEntity.setPromotionAmount(promotion);
        orderEntity.setIntegrationAmount(integration);
        orderEntity.setCouponAmount(coupon);

        //设置积分等信息
        orderEntity.setIntegration(gift.intValue());
        orderEntity.setGrowth(growth.intValue());
        orderEntity.setDeleteStatus(0);//未删除

    }

    private OrderEntity buildOrder(String ordersn) {
        MemberResponseVo memberResponseVo = LoginInterceptor.loginUser.get();
        OrderEntity orderEntity = new OrderEntity();
        orderEntity.setOrderSn(ordersn);
        orderEntity.setMemberId(memberResponseVo.getId());

        //获取收货地址信息
        OrderSubmitVo orderSubmitVo = submitThreadLocal.get();
        R fare = wmsFeignService.getFare(orderSubmitVo.getAddrId());
        FareVo fareResp = fare.getData(new TypeReference<FareVo>() {
        });

        //设置运费信息
        orderEntity.setFreightAmount(fareResp.getFare());
        //设置收货人信息
        orderEntity.setReceiverCity(fareResp.getAddress().getCity());
        orderEntity.setReceiverDetailAddress(fareResp.getAddress().getDetailAddress());
        orderEntity.setReceiverName(fareResp.getAddress().getName());
        orderEntity.setReceiverPhone(fareResp.getAddress().getPhone());
        orderEntity.setReceiverPostCode(fareResp.getAddress().getPostCode());
        orderEntity.setReceiverProvince(fareResp.getAddress().getProvince());
        orderEntity.setReceiverRegion(fareResp.getAddress().getRegion());

        //设置订单的相关状态信息
        orderEntity.setStatus(OrderStatusEnum.CREATE_NEW.getCode());
        orderEntity.setAutoConfirmDay(7);

        return orderEntity;
    }

    /**
     * 构建所有订单项数据
     *
     * @param ordersn
     * @return
     */
    private List<OrderItemEntity> buildOrderItems(String ordersn) {
        List<OrderItemVo> currentUserCartItems = cartFeignService.getCurrentUserCartItems();
        if (currentUserCartItems != null && currentUserCartItems.size() > 0) {
            List<OrderItemEntity> itemEntities = currentUserCartItems.stream().map(cartItem -> {
                OrderItemEntity itemEntity = buildOrderItem(cartItem);
                itemEntity.setOrderSn(ordersn);
                return itemEntity;
            }).collect(Collectors.toList());
            return itemEntities;
        }
        return null;
    }

    /**
     * 构建某一个订单项
     *
     * @param cartItem
     * @return
     */
    private OrderItemEntity buildOrderItem(OrderItemVo cartItem) {
        OrderItemEntity itemEntity = new OrderItemEntity();
        //1、订单信息：订单号
        //2、商品spu信息
        Long skuId = cartItem.getSkuId();
        R r = productFeignService.getSpuInfoBySkuId(skuId);
        SpuInfoVo data = r.getData(new TypeReference<SpuInfoVo>() {
        });
        itemEntity.setSpuId(data.getId());
        itemEntity.setSpuBrand(data.getBrandId().toString());
        itemEntity.setSpuName(data.getSpuName());
        itemEntity.setCategoryId(data.getCatalogId());
        //3、商品sku信息
        itemEntity.setSkuId(cartItem.getSkuId());
        itemEntity.setSkuName(cartItem.getTitle());
        itemEntity.setSkuPrice(cartItem.getPrice());
        itemEntity.setSkuPic(cartItem.getImage());
        String skuAttr = StringUtils.collectionToDelimitedString(cartItem.getSkuAttr(), ";");
        itemEntity.setSkuAttrsVals(skuAttr);
        itemEntity.setSkuQuantity(cartItem.getCount());
        //4、优惠券信息【不做】
        //5、积分信息
        itemEntity.setGiftGrowth(cartItem.getPrice().multiply(new BigDecimal(cartItem.getCount().toString())).intValue());
        itemEntity.setGiftIntegration(cartItem.getPrice().multiply(new BigDecimal(cartItem.getCount().toString())).intValue());

        //6、订单项的价格信息
        itemEntity.setPromotionAmount(new BigDecimal("0"));
        itemEntity.setCouponAmount(new BigDecimal("0"));
        itemEntity.setIntegrationAmount(new BigDecimal("0"));
        //当前订单项的实际金额，总额-各种优惠
        BigDecimal orgin = itemEntity.getSkuPrice().multiply(new BigDecimal(itemEntity.getSkuQuantity().toString()));
        BigDecimal subtract = orgin.subtract(itemEntity.getCouponAmount())
                .subtract(itemEntity.getPromotionAmount())
                .subtract(itemEntity.getIntegrationAmount());
        itemEntity.setRealAmount(subtract);

        return itemEntity;
    }

}